﻿using System;
using System.Linq;
using System.Collections.Generic;

using SimpleForum.Utils;
using SimpleForum.Data.Models;
using SimpleForum.Data.Repositories;

namespace SimpleForum.Data.Services
{
    public class ThreadService : IThreadService
    {
        private readonly IRepository<Thread> ThreadRepository;
        private readonly UserService UserService;
        private readonly TagService TagService;

        public ThreadService(IRepository<Thread> ThreadRepository, UserService UserService, TagService TagService)
        {
            this.ThreadRepository = ThreadRepository;
            this.UserService = UserService;
            this.TagService = TagService;
        }

        public Thread GetThread(int Id)
        {
            return ThreadRepository.Get(Id);
        }

        public IEnumerable<Thread> GetThreads()
        {
            return ThreadRepository.Get();
        }

        public void ThreadViewed(Thread Thread)
        {
            Thread.Views++;
            ThreadRepository.Update(Thread);
        }

        public Thread CreateThread(int ForumId, int UserId, string Title, string Message, string Tags = null)
        {
            var Thread = new Thread
            {
                ForumId = ForumId,
                CreatorId = UserId,
                Name = Title,
                Views = 0,
                CreatedDate = DateTime.UtcNow
            };

            if (Tags != null) TagService.AddTagsToThread(Thread, Tags);

            // create the first post in the thread
            Thread.Posts.Add(new Post
            {
                Body = Message,
                CreatedDate = DateTime.UtcNow,
                CreatorId = UserId,
                ThreadId = Thread.Id
            });

            // give the creator 10 reputation for creating a new thread...
            UserService.AddReputation(UserId, Services.UserService.ReputationType.CreateThread, "thread/" + Thread.Id + "/" + Title.Slugify());

            // save the thread to the db
            return ThreadRepository.Add(Thread);
        }
    }
}